package app

import (
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/CIPFZ/collector/internal/vars"
	
	"go.uber.org/zap"
)

// SetupSignalHandling 设置信号处理
func SetupSignalHandling(c *Collector) {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)

	go func() {
		// 等待第一次信号来
		sig := <-sigCh
		c.Logger().Info("Received termination signal, gracefully shutting down...", zap.String("signal", sig.String()))
		_ = c.Shutdown()

		// 等待第二次信号强制退出 或者 超时推出
		c.Logger().Info("Waiting for a second signal to force shutdown or timeout...",
			zap.String("timeout", vars.ForceExitTimeout.String()))

		select {
		case sig2 := <-sigCh:
			c.Logger().Warn("Force shutdown triggered by second signal...",
				zap.String("signal", sig2.String()))
			os.Exit(vars.ExitCodeCanceled)
		case <-time.After(vars.ForceExitTimeout):
			c.Logger().Warn("Force shutdown due to timeout...")
			os.Exit(vars.ExitCodeCanceled)
		}
	}()
}
